import {defineStore} from "pinia";
import {computed, ref} from "vue";
import type {ComputedRef, Ref} from "vue";
import router from "@/router";
import staticRoutes from "@/router/modules";
import _ from "lodash";
import type {RouteRecordNormalized} from "vue-router";


export const useMenu = defineStore("menu", () => {

    const routeMenus: Ref<RouteRecordNormalized[]> = ref([]);
    const sideMenus: ComputedRef<RouteRecordNormalized[]> = computed(() => {
        let routes = routeMenus.value;
        routes = routes.filter(x => x.meta.level === 1 && !x.meta.hidden);
        routes = routes.sort((a, b) => {
            return (a.meta?.index ?? 0) - (b.meta?.index ?? 0);
        });
        routes.forEach(item => {
            item.children = item.children.filter(c => !c.meta?.hidden);
        });
        return routes;
    });

    function isEmptyRouteMenus() {
        return !(routeMenus.value && routeMenus.value.length);
    }

    function initRouteMenus() {
        let allRoutes = _.cloneDeep(staticRoutes);

        allRoutes.forEach(route => router.addRoute("Layout", route));
        routeMenus.value = router.getRoutes();
    }

    return {routeMenus, sideMenus, isEmptyRouteMenus, initRouteMenus};
});